<template>
  <div class="mian">
    <p>原网站：https://www.aitaotu.com/</p>
    <p>
      <el-input v-model="html"></el-input>
    </p>
    <p>
      <el-button @click="readHtml(html)">读取</el-button>
    </p>
    <p>共： {{num}}</p>
    <p>标题： {{title}}</p>
    <p>
      <el-button @click="getimg">下载</el-button>
    </p>
  </div>
</template>

<script>
const cheerio = require("cheerio");
const request = require("request");
const fs = require("fs");

export default {
  name: "",

  data() {
    return {
      imgs: [],
      html: "",
      num: 0,
      title: ""
    };
  },
  mounted() {},
  methods: {
    xjb(url) {},
    readHtml(url) {
      this.imgs = [];
      let baseUrl = url.split(".html")[0];
      console.log(baseUrl);
      let that = this;
      // let url = "https://www.aitaotu.com/meinv/53592.html";
      request(url, (error, response, body) => {
        if (!error && response.statusCode == 200) {
          let $ = cheerio.load(body);
          let num = $("h1 #picnum .totalpage")[0].children[0].data;
          this.num = num;
          this.title = $("h1")[0].children[0].data;
          console.log(this.title);

          fs.mkdir(this.title, function(error) {
            if (error) {
              console.log(error);
              return false;
            }
            console.log("创建目录成功");
          });

          let arr = getAll(num);
          getURl(arr);
        }
      });
      function getAll(num) {
        let arr = [];

        for (let i = 0; i < num; i++) {
          let url = "";
          if (i == 0) {
            url = baseUrl + ".html";
          } else {
            url = baseUrl + "_" + +(i + 1) + ".html";
          }
          arr.push(url);
        }
        //   console.log(arr);
        return arr;
      }
      function getURl(arr) {
        for (let i = 0; i < arr.length; i++) {
          let url = arr[i];
          request(url, (error, response, body) => {
            if (!error && response.statusCode == 200) {
              let $ = cheerio.load(body);
              let img_url = [];
              img_url.push($("#big-pic img")[0].attribs.src);
              img_url.push(url);
              that.imgs.push(img_url);
            }
          });
        }
      }
    },
    getimg() {
      let arr = this.imgs;
      for (let i = 0; i < arr.length; i++) {
        let url = {
          url: arr[i][0],
          headers: {
            Referer: arr[i][1],
            responseType: "arraybuffer"
          }
        };
        request(url, (error, response, body) => {}).pipe(
          fs.createWriteStream(`${"./" + this.title}/${i}.jpg`)
        );
      }
    }
  }
};
</script>

<style lang="less" scoped>
.mian {
  padding: 30px;
  > p {
    line-height: 60px;
  }
}
</style>
